<?php

namespace App\Jobs\Cruise;

use App\Models\Common\FileTranscodingJobModel;
use App\Models\Cruise\CruiseOrderInputModel;
use App\Models\Cruise\CruiseOrderModel;
use App\Models\File\FileProcessingModel;
use Carbon\Carbon;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Kuafu\File\FileUtil;

class CruiseCheckInputUploadTranscoding implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    protected int    $cruiseOrderId;
    protected int    $userId;
    protected string $field;
    protected        $value;
    protected array  $auditValue;

    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct($cruiseOrderId, $userId, $field, $value, $auditValue)
    {
        $this->cruiseOrderId = $cruiseOrderId;
        $this->userId        = $userId;
        $this->field         = $field;
        $this->value         = $value;
        $this->auditValue    = $auditValue;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        // 有文件才会验证
        $filePathList = $this->auditValue['files'] ?? [];

        $attendCount   = 0;
        $completeCount = 0;

        $replacePathList = [];

        foreach ($filePathList as $filePath) {
            $path       = $filePath['path'] ?? '';
            $domainPath = $filePath['url'] ?? '';
            $type       = $filePath['type'] ?? '';

            if (!in_array($type, ['video', 'image'])) {
                continue;
            }

            if (!strlen($path) || strpos($domainPath, FileUtil::domain()) === false || strpos($path, '_encoded') !== false) {
                continue;
            }

            $haveFile = null;
            // 查询转码任务中是否含有此视频
            switch ($type) {
                case 'image':
                    $haveFile = FileProcessingModel::query()
                        ->where('beforeUri', $path)
                        ->first();

                    break;
                case 'video':
                    $haveFile = FileTranscodingJobModel::query()
                        ->where('filePath', $path)
                        ->first();

                    break;
                default:
            }

            if (!$haveFile) {
                continue;
            } else {
                $attendCount++;
            }

            switch ($type) {
                case 'image':
                    if ($haveFile->status == FileProcessingModel::STATUS_FINISH) {
                        $replacePathList[$path] = $haveFile->afterUri;
                        $completeCount++;
                    }
                    break;
                case 'video':
                    if ($haveFile->status == FileTranscodingJobModel::STATUS_OK) {
                        $replacePathList[$path] = $haveFile->filePathEncoded;
                        $completeCount++;
                    }
                    break;
                default:
            }
        }

        Log::info('添加水印替换 Json: ' . json_encode($replacePathList));

        if ($attendCount != 0) {
            if ($attendCount == $completeCount) {
                // 获得表单
                $type = (int)CruiseOrderModel::query()->where('id', $this->cruiseOrderId)->value('type');

                $inputId = CruiseOrderInputModel::query()
                    ->where('orderId', $this->cruiseOrderId)
                    ->where('templateType', $type)
                    ->value('id');

                DB::beginTransaction();
                try {
                    $cruiseOrderInputModel = CruiseOrderInputModel::query()
                        ->where('id', $inputId)
                        ->lockForUpdate()
                        ->first();

                    if ($cruiseOrderInputModel) {
                        $userContentJson = $cruiseOrderInputModel->userContentJson;

                        // 字符串替换
                        foreach ($replacePathList as $oldPath => $replacePath) {
                            $userContentJson = str_replace($oldPath, $replacePath, $userContentJson);
                        }

                        $cruiseOrderInputModel->userContentJson = $userContentJson;
                        $cruiseOrderInputModel->save();
                    }
                    DB::commit();
                } catch (\Exception $exception) {
                    DB::rollBack();
                }
            } else {
                $job = (new CruiseCheckInputUploadTranscoding($this->cruiseOrderId, $this->userId, $this->field, $this->value, $this->auditValue))->delay(Carbon::now()->addSeconds(10));
                dispatch($job);
            }
        }
    }
}
